package base

import (
	"context"
	"rewords-server-2024/internal/consts"
	"rewords-server-2024/internal/model/entity"
	"rewords-server-2024/internal/model/input/query_in"
	"rewords-server-2024/internal/service"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"

	"github.com/gogf/gf/v2/errors/gerror"

	"rewords-server-2024/api/base/system"
)

func (c *ControllerSystem) SysUserInfoList(ctx context.Context, req *system.SysUserInfoListReq) (res *system.SysUserInfoListRes, err error) {
	g.Log().Print(ctx, req)

	// 构建查询条件和分页参数
	query, skip, limit, sort, projection := query_in.BuildMongoQueryWithPage(req.Conditions, req.OrderFields, req.Page, []string{})
	g.Log().Debug(ctx, "MongoDB query conditions:", query)
	g.Log().Debug(ctx, "Skip:", skip, "Limit:", limit)
	g.Log().Debug(ctx, "Sort:", sort)
	g.Log().Debug(ctx, "Projection:", projection)

	// 获取总记录数
	total, err := service.Mgx().CountDocuments(ctx, consts.CUser, query)
	if err != nil {
		return nil, gerror.Wrap(err, "获取总记录数失败")
	}

	result, err := service.Mgx().Find(ctx, consts.CUser, query, projection, skip, limit, sort)
	if err != nil {
		return nil, gerror.Wrap(err, "获取数据失败")
	}

	// 将 result 转换为所需的结构体切片
	var users []entity.SysUser
	if err = gconv.Struct(result, &users); err != nil {
		return nil, gerror.Wrap(err, "数据转换失败")
	}

	//data, err := cmgo.Find("sys_user", query, query_in.Fields, skip, limit, sort)
	res = &system.SysUserInfoListRes{
		Data: users,
		PageResult: query_in.PageResult{
			Current:  (skip / limit) + 1,          // 当前页码
			PageSize: limit,                       // 每页条数
			Total:    total,                       // 总记录数
			Pages:    (total + limit - 1) / limit, // 总页数
			HasNext:  (skip + limit) < total,      // 是否有下一页
		},
	}

	return res, nil
}
